﻿using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using DevManager.Models;
using DevManager.Services;
using DevManager.StatusBars;
using FluentAvalonia.UI.Controls;
using FluentAvalonia.UI.Navigation;
using FluentAvalonia.UI.Windowing;

namespace DevManager.Views;

public partial class MainView : UserControl
{
    public LanguageModel Info { get; private set; }

    public MainView()
    {
        InitializeComponent();
        Info = new LanguageModel(LanguageService.GetList()!);
    }

    #region Init

    protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        FrameView.IsNavigationStackEnabled = true;
        FrameView.NavigationPageFactory = new NavigationFactory();
        Navigate("Home");
    }

    protected override void OnLoaded(RoutedEventArgs e)
    {
        base.OnLoaded(e);

        if (VisualRoot is AppWindow aw)
        {
            TitleBarHost.ColumnDefinitions[3].Width = new GridLength(aw.TitleBar.RightInset, GridUnitType.Pixel);
        }
    }

    #endregion


    private void ItemInvoked(object? sender, NavigationViewItemInvokedEventArgs e)
    {
        if (e.InvokedItemContainer.Tag is not string s) return;
        if (string.IsNullOrEmpty(s)) return;
        Navigate(s);
    }

    public void Navigate(string page)
    {
        page = page.Replace(" ", "");
        FrameView.Navigate(Type.GetType($"DevManager.Pages.{page}Page"));
    }

    public void Navigate(object context)
    {
        FrameView.NavigateFromObject(context, new FrameNavigationOptions());
    }

    private void OnBackRequested(object? sender, NavigationViewBackRequestedEventArgs e)
    {
        FrameView.GoBack();
    }
    
    private void BackClick(object? sender, RoutedEventArgs e)
    {
        FrameView.GoBack();
    }

    private void Navigated(object sender, NavigationEventArgs e)
    {
    }

    [Obsolete("虽然我知道WebClient已经过时了，但是现在还没办法")]
    public void Download(string url, string path, string name)
    {
        Item.Content = new DownloadBar(new DownloadModel() { Url = url, FilePath = path, Name = name });
    }
}